package com.my.algorithmlearning.leetcode;

/**
 * @ClassName Medium_200_IslandNums
 * @Description 优秀题解：https://leetcode.cn/problems/number-of-islands/solutions/211211/dao-yu-lei-wen-ti-de-tong-yong-jie-fa-dfs-bian-li-/
 * @Author wanghaiwei
 * @Date 2023/6/14 10:26
 */
public class Medium_200_IslandNums {
    public static void main(String[] args) {
        Medium_200_IslandNums islandNums = new Medium_200_IslandNums();
        char[][] input = new char[][]{{'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}};
        System.out.println(islandNums.numIslands(input));
    }

    public int numIslands(char[][] grid) {
        int nums = 0;
        if (grid == null || grid.length == 0) {
            return nums;
        }
        int row = grid.length;
        int col = grid[0].length;
        for (int r = 0; r < row; r++) {
            for (int c = 0; c < col; c++) {
                if (grid[r][c] == '1') {
                    nums++;
                    dfs(grid, r, c);
                }
            }
        }
        return nums;
    }

    private void dfs(char[][] grid, int r, int c) {
        if (outOfRange(r, c, grid) || grid[r][c] == '2' || grid[r][c] == '0') {
            return;
        }
        grid[r][c] = '2';
        dfs(grid, r - 1, c);
        dfs(grid, r + 1, c);
        dfs(grid, r, c - 1);
        dfs(grid, r, c + 1);
    }

    private boolean outOfRange(int r, int c, char[][] grid) {
        return r < 0 || r >= grid.length || c < 0 || c >= grid[0].length;
    }
}
